﻿using System.Collections.Generic;
using Gp.Examples.FullCalendar.Core;
using Gp.Examples.FullCalendar.Core.Repository;
using Gp.Examples.FullCalendar.Infrastructure;
using NHibernate;
using NHibernate.Criterion;

namespace Gp.Examples.FullCalendar.Data.NHibernate.Repository
{
    public class UserRepository : IUserRepository
    {
        private ISession Session { get; set; }

        public UserRepository(IMapper mapper)
        {
            Session = mapper.CurrentSession as ISession;
        }

        public IList<User> ListUsers()
        {
            var criteria = Session.CreateCriteria(typeof(User));
            criteria.AddOrder(new Order("UserName", true));

            var users = criteria.List<User>();
            return users;
        }

        public void Delete(User user)
        {
            Session.Delete(user);
        }

        public void DeleteUserByUserName(string userName)
        {
            var user = GetUserByUserName(userName);
            if (user == null)
                return;

            Delete(user);
        }

        public User GetUserByEmail(string email)
        {
            var queryString = "from User u where u.Email=?";
            var query = Session.CreateQuery(queryString);
            query.SetParameter(0, email);

            return query.UniqueResult<User>();
        }

        public User GetUserByLiveIdHash(string liveIdHash)
        {
            var queryString = "from User u where u.LiveIdHash=?";
            var query = Session.CreateQuery(queryString);
            query.SetParameter(0, liveIdHash);

            return query.UniqueResult<User>();
        }

        public User GetUserByUserName(string userName)
        {
            var queryString = "from User u where u.UserName=?";
            var query = Session.CreateQuery(queryString);
            query.SetParameter(0, userName);

            return query.UniqueResult<User>();
        }

        public void Save(User user)
        {
            Session.SaveOrUpdate(user);
        }
    }
}
